const stream_url = `${window.location.origin}/StreamUrl`;
const helper = new Helper(this, true);
const prefix = helper.getVariable('environmentType');
const videoPlatform = helper.getVariable('videoPlatform');
// 基础服务
const basicRequest = BasicServices.getInstance(prefix);
// 流媒体服务
const streamRequest = StreamServices.getInstance(prefix);
// 应急服务
const emergencyRequest = EmergencyServices.getInstance(prefix);
// 物联 service
const iotServiceRequest = IotServiceServices.getInstance(prefix);

const tabs = {
    /**
     * 获取按钮组件
     *
     * @return {{all: *, offline: *, online: *}}
     */
    getAllBtn() {
        return {
            all: helper.get('devices_all'),
            online: helper.get('devices_online'),
            offline: helper.get('devices_offline'),
        }
    },
    /**
     * 设置css
     *
     * @param active
     * @param others
     */
    setCss(active, others = []) {
        $(active.__box).css("box-shadow", "inset 0 -5px 8px var(--active-color)");
        others.forEach(item => {
            $(item.__box).css("box-shadow", "inset 0 0 5px var(--body-bg)");
        })
    },
    // 选中全部
    all() {
        const { all, online, offline } = tabs.getAllBtn();
        tabs.setCss(all, [online, offline]);
    },
    // 选中在线
    online() {
        const { all, online, offline } = tabs.getAllBtn();
        tabs.setCss(online, [all, offline]);
    },
    // 选中离线
    offline() {
        const { all, online, offline } = tabs.getAllBtn();
        tabs.setCss(offline, [all, online]);
    }
}

helper.log?.('页面初始化前')
// 公共请求方法
const baseRequest = function (url, body, method) {
    const controller = new AbortController();
    setTimeout(() => controller.abort(), 20000);
    const headers = { "Content-Type": "application/json" };
    const option = { method, headers, body: JSON.stringify(body), signal: controller.signal };
    return fetch(url, option).then(res => res.json());
}

// 监控视图数据处理
const handleMonitorData = async function () {
    const dataSource = [
        { id: "0", viewType: 0, viewName: "公有视图", monitorLevel: 'root' },
        { id: "1", viewType: 1, viewName: "私有视图", monitorLevel: 'root' }
    ];
    const res = await emergencyRequest.videoViewListByViewName(window._videoAccess.monitorSearch);
    const result = res || [];
    dataSource.forEach(item => {
        item.children = result.filter(i => i.viewType === item.viewType);
    });
    const monitor = helper.get('monitor').widgetObj;
    monitor.option_data = dataSource;
    monitor.tree.expandSelected = new Set();
    monitor.render();
    console.log('MonitorData: => ', dataSource);
    const monitorData = window._videoAccess.monitorSelect;
    console.log(monitorData, 'monitorData')
    if (monitorData?.id && monitorData?.operate !== 'delete') {
        const item = result.find(i => i.id === monitorData?.id);
        if (item) window._videoAccess.monitorSelect = item;
        const node = $(monitor.container).find(`#${window._videoAccess.monitorSelect?.id}`);
        node.addClass('tree_node_active');
    } else {
        window._videoAccess.monitorSelect = undefined;
    }
}

// 获取当前视频数据
const handleSullivanData = function () {
    const sullivan = helper.get('三维组件')?.widgetObj.sullivan;
    const cameraMap = sullivan.cameraMap || new Map();
    const grid = sullivan.grid || [3, 3];
    const videoViewDetails = [];
    cameraMap.forEach((item, index) => {
        const data = item.data || {};
        videoViewDetails.push({
            location: index,
            equipmentId: data?.equipmentCode,
            equipmentInfo: JSON.stringify(data),
        })
    })
    console.log(videoViewDetails, 'videoViewDetails')
    return { videoViewDetails, layout: JSON.stringify(grid) };
}

// 处理设备列表树数据
function handleRows(data, rows, id) {
    return data.map(item => {
        if (item.id === id) return { ...item, isFetch: true, children: rows };
        if (item.children && item.children.length) {
            return { ...item, children: handleRows(item.children, rows, id) }
        }
        return item;
    })
}
function findParentNodes(tree, targetId, path = []) {
    for (const node of tree) {
        if (node.id === targetId) {
            return path;
        }
        if (node.children) {
            const result = findParentNodes(node.children, targetId, [...path, node.id]);
            if (result) {
                return result;
            }
        }
    }
    return null;
}
function extractNumber(input) {
    const regex = /\((\d+)\)/;
    const match = input.match(regex);
    if (!match || !match[1]) {
        return null;
    }
    return parseInt(match[1], 10);
}
function nodeHtmlText(id) {
    const node = $(`#${id}`).find('.tree-title')[0]
    const text = node.innerText.split('(')[0]
    const number = extractNumber(node.innerText) - 1
    node.innerText = text + '(' + number + ')'
}
// 设置设备列表树数据
function renderTree(rows, id, isDel) {
    const devices = helper.get('devices').widgetObj;
    const { dataSource } = devices._option;
    if (dataSource && +id !== -1) {
        let data = handleRows(dataSource, rows, id);
        console.log(data, rows, 'data')
        // if(isDel) {
        //     const parentIds = findParentNode(data, id)
        //     const arr = tree2arr(data)
        //     const treeData = data.map((vl) => {
        //         const item = {
        //             ...v
        //         }
        //         if(parentIds.find(p=> p.id === vl.id)) {
        //             item.title = ''
        //         }
        //         return item
        //     })
        // }
        devices.setData([{ data }]);

        if (isDel) {
            const parentIds = findParentNodes(data, id)
            nodeHtmlText(id)
            parentIds.forEach(ve => {
                nodeHtmlText(ve)
            })
        }
    } else {
        devices.option_data = handleRows(rows);
        devices.tree.expandSelected = new Set();
    }

    devices.tree.expandSelected.add(id);
    devices.render();
}

// 设备数据处理
function handleEquipmentData(data) {
    const { equipmentName, equipmentCode, equipmentId, logicStatus, equipmentConfig } = data || {};
    const gbVideoConfig = equipmentConfig?.gbVideoConfig || {};
    let channelId = gbVideoConfig?.videoChannelId;
    let deviceId = gbVideoConfig?.sipUser;
    let stream_path;
    if (channelId && deviceId) stream_path = `${deviceId}/${channelId}`;
    /*const onlineImage = `<svg style="width: 20px;height: 20px;" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" width="200" height="200">
        <path d="M514.708995 382.871252c-59.597884 0-108.359788 48.761905-108.359789 108.359789s48.761905 108.359788 108.359789 108.359788 108.359788-48.761905 108.359788-108.359788-48.761905-108.359788-108.359788-108.359789zM469.559083 484.007055c-21.671958 0-39.731922-18.059965-39.731923-39.731923 0-21.671958 18.059965-39.731922 39.731923-39.731922s39.731922 18.059965 39.731922 39.731922c0 23.477954-18.059965 39.731922-39.731922 39.731923zM437.051146 700.726631h144.479718v90.299824h-144.479718z" fill="#C0EAFF" p-id="5381"></path>
    <path d="M511.097002 731.428571c-144.479718 0-261.869489-117.389771-261.869489-261.869488 0-41.537919 9.029982-81.269841 27.089947-117.389771 3.611993-9.029982 14.447972-12.641975 23.477954-7.223986s12.641975 14.447972 7.223986 23.477954c-16.253968 30.70194-23.477954 65.015873-23.477954 101.135803 0 124.613757 101.135802 225.749559 225.749559 225.749559S736.846561 594.17284 736.846561 469.559083s-101.135802-225.749559-225.749559-225.749559c-52.373898 0-102.941799 18.059965-142.673722 50.567901-7.223986 7.223986-19.865961 5.417989-25.28395-1.805996-7.223986-7.223986-5.417989-19.865961 1.805996-25.283951 46.955908-37.925926 106.553792-59.597884 166.151676-59.597884 144.479718 0 261.869489 117.389771 261.869488 261.869489s-117.389771 261.869489-261.869488 261.869488z" fill="#1F87DD" p-id="5382"></path><path d="M511.097002 617.650794c-72.239859 0-131.837743-59.597884-131.837743-131.837743s59.597884-131.837743 131.837743-131.837742 131.837743 59.597884 131.837742 131.837742-59.597884 131.837743-131.837742 131.837743z m0-225.749559c-52.373898 0-95.717813 43.343915-95.717813 95.717813s43.343915 95.717813 95.717813 95.717813 95.717813-43.343915 95.717813-95.717813-43.343915-95.717813-95.717813-95.717813z" fill="#1F87DD" p-id="5383"></path><path d="M511.097002 297.989418m-23.477954 0a23.477954 23.477954 0 1 0 46.955908 0 23.477954 23.477954 0 1 0-46.955908 0Z" fill="#1F87DD" p-id="5384"></path><path d="M583.336861 816.310406h-144.479718c-10.835979 0-18.059965-7.223986-18.059965-18.059965v-43.343915c0-10.835979 7.223986-18.059965 18.059965-18.059965s18.059965 7.223986 18.059965 18.059965v25.28395h108.359788v-74.045855c0-10.835979 7.223986-18.059965 18.059965-18.059965s18.059965 7.223986 18.059964 18.059965v92.10582c0 9.029982-7.223986 18.059965-18.059964 18.059965z" fill="#1F87DD" p-id="5385"></path><path d="M680.86067 816.310406H343.13933c-10.835979 0-18.059965-7.223986-18.059965-18.059965s7.223986-18.059965 18.059965-18.059965h337.72134c10.835979 0 18.059965 7.223986 18.059965 18.059965s-9.029982 18.059965-18.059965 18.059965z" fill="#1F87DD" p-id="5386"></path>
</svg>`*/
    const onlineImage = `<div style="width: 20px;min-width: 20px;height: 20px;margin-right: 5px;background: var(--equipment-online-status) no-repeat; background-size: 20px 20px;"></div>`
    const offlineImage = '<svg style="width: 24px;min-width: 24px;height: 24px;transform: translateX(-5px);"' +
        ' viewBox="0 0 824 824"' +
        ' xmlns="http://www.w3.org/2000/svg" width="200" height="200"><path d="M514.708995 382.871252c-59.597884 0-108.359788 48.761905-108.359789 108.359789s48.761905 108.359788 108.359789 108.359788 108.359788-48.761905 108.359788-108.359788-48.761905-108.359788-108.359788-108.359789zM469.559083 484.007055c-21.671958 0-39.731922-18.059965-39.731923-39.731923 0-21.671958 18.059965-39.731922 39.731923-39.731922s39.731922 18.059965 39.731922 39.731922c0 23.477954-18.059965 39.731922-39.731922 39.731923zM437.051146 700.726631h144.479718v90.299824h-144.479718z" fill="#8a8a8a" p-id="5381"></path><path d="M511.097002 731.428571c-144.479718 0-261.869489-117.389771-261.869489-261.869488 0-41.537919 9.029982-81.269841 27.089947-117.389771 3.611993-9.029982 14.447972-12.641975 23.477954-7.223986s12.641975 14.447972 7.223986 23.477954c-16.253968 30.70194-23.477954 65.015873-23.477954 101.135803 0 124.613757 101.135802 225.749559 225.749559 225.749559S736.846561 594.17284 736.846561 469.559083s-101.135802-225.749559-225.749559-225.749559c-52.373898 0-102.941799 18.059965-142.673722 50.567901-7.223986 7.223986-19.865961 5.417989-25.28395-1.805996-7.223986-7.223986-5.417989-19.865961 1.805996-25.283951 46.955908-37.925926 106.553792-59.597884 166.151676-59.597884 144.479718 0 261.869489 117.389771 261.869488 261.869489s-117.389771 261.869489-261.869488 261.869488z" fill="#8a8a8a" p-id="5382"></path><path d="M511.097002 617.650794c-72.239859 0-131.837743-59.597884-131.837743-131.837743s59.597884-131.837743 131.837743-131.837742 131.837743 59.597884 131.837742 131.837742-59.597884 131.837743-131.837742 131.837743z m0-225.749559c-52.373898 0-95.717813 43.343915-95.717813 95.717813s43.343915 95.717813 95.717813 95.717813 95.717813-43.343915 95.717813-95.717813-43.343915-95.717813-95.717813-95.717813z" fill="#8a8a8a" p-id="5383"></path><path d="M511.097002 297.989418m-23.477954 0a23.477954 23.477954 0 1 0 46.955908 0 23.477954 23.477954 0 1 0-46.955908 0Z" fill="#8a8a8a" p-id="5384"></path><path d="M583.336861 816.310406h-144.479718c-10.835979 0-18.059965-7.223986-18.059965-18.059965v-43.343915c0-10.835979 7.223986-18.059965 18.059965-18.059965s18.059965 7.223986 18.059965 18.059965v25.28395h108.359788v-74.045855c0-10.835979 7.223986-18.059965 18.059965-18.059965s18.059965 7.223986 18.059964 18.059965v92.10582c0 9.029982-7.223986 18.059965-18.059964 18.059965z" fill="#8a8a8a" p-id="5385"></path><path d="M680.86067 816.310406H343.13933c-10.835979 0-18.059965-7.223986-18.059965-18.059965s7.223986-18.059965 18.059965-18.059965h337.72134c10.835979 0 18.059965 7.223986 18.059965 18.059965s-9.029982 18.059965-18.059965 18.059965z" fill="#8a8a8a"></path></svg>'
    let online = 1;
    if (equipmentConfig?.equipmentUnifyConfig) {
        online = equipmentConfig.equipmentUnifyConfig.onlineStatus
    }
    /**
     * onlineStatus: { 0: 在线, 1: 离线, 2: 异常 }
     */
    return {
        ...data,
        title: equipmentName,
        stream_path,
        channelId,
        deviceId,
        onlineStatusImage: online === 0 ? onlineImage : offlineImage,
        isDraggable: !online,
        equipmentId: equipmentId || equipmentCode,
        url: `${stream_url}/api/v1/stream/rtc/play`,
    }
}

function handleFuseData(data) {
    return {
        ...data,
        title: data.fuseName,
        type: 'fuse',
        iconType: 'fuse',
        onlineStatusImage: globalTheme.video_quota_icon,
        url: `${stream_url}/api/v1/stream/rtc/play`,
    }
}

// 区域数据处理
function handleAreaData(data, projectCode) {
    if (!data || !data.length) return [];
    return data.map(item => ({
        ...item,
        title: `${item.projectName || item.projectAreaName}(${item.equipmentCount})`,
        type: 'area',
        projectCode: projectCode || item.projectCode,
        children: [],
        isDraggable: false,
    }))
}

// 查询区域数据 - 新版本接口
const queryQuotaByArea = async (parentProjectAreaId, projectCode) => {
    const result = await emergencyRequest.queryQuotaWithProjectArea({
        equipmentStatus: window._videoAccess.equipmentStatus,
        parentProjectAreaId,
        equipmentName: _videoAccess.equipmentSearch,
    });
    // layer.close(loading);
    const { areaList = [], equipmentList = [], videoFuses = [] } = result || {}
    const areaRows = handleAreaData(areaList, projectCode);
    const equipmentRows = (equipmentList).map(item => handleEquipmentData(item));
    const fusesRows = (videoFuses).map(item => handleFuseData(item));
    return { areaRows, equipmentRows, fusesRows };
}

// 查询融合视频数据
const queryFuseData = async (projectCode) => {
    // const loading = layer.load(0);
    const res = await emergencyRequest.getVideoFuse(_videoAccess.equipmentSearch, projectCode);
    // layer.close(loading);
    return (res?.result || []).map(item => ({
        ...item,
        title: item.fuseName,
        type: 'fuse',
    }));
}

// 设备树数据处理
const handleEquipmentTreeData = async function (equipmentStatus) {
    const equipmentName = window._videoAccess.equipmentSearch
    // const loading = layer.load(0);
    const result = await emergencyRequest.queryProjectByEquipmentStatus({ equipmentName, equipmentStatus }) || [];
    // layer.close(loading);
    const dataSource = handleAreaData(result) || []
    console.log(dataSource, 'dataSource222');
    const devices = helper.get('devices').widgetObj;
    devices.option_data = dataSource;
    devices.tree.expandSelected = new Set();
    devices.render();
}

// 查询海康视频流
async function getHikData(params) {
    const { expand, protocol = "hls,rtsp", streamType = 0, streamform, transmode = 0 } = params;
    const cameraIndexCode = params.equipmentId || params.equipmentCode;
    const result = await iotServiceRequest.getPreviewByEquipmentId(
        { cameraIndexCode, expand, protocol, streamType, streamform, transmode }
    );
    return result?.url ? JSON.parse(result.url) : false;
}


// 查询视频融合流地址
async function getFuse(data) {
    layer.msg('融合视频加载中');
    const fuseDetails = (data.videoFuseDetails || []).map(item => JSON.parse(item.equipmentInfo));
    return await getFuseByEquipmentInfo(fuseDetails, data);
}

/**
 * 查询视频融合流地址
 *
 * @param fuseDetails
 * @param data
 * @return {Promise<{[p: string]: *}|boolean>}
 */
async function getFuseByEquipmentInfo(fuseDetails, data = {}) {
    layer.msg('融合视频加载中');
    // const loading = layer.load(0);
    let body = {};
    if (videoPlatform === 'security') {
        const hikData = await Promise.all(fuseDetails.map(item => getHikData(item)));
        body.urls = (hikData || []).map(item => item.urls.rtsp);
    } else {
        body.local_stream_paths = fuseDetails.map(item => item.stream_path);
    }
    const result = await streamRequest.streamStitch(body, data?.id);
    // layer.close(loading);
    if (result) return { ...data, ...result };
    layer.msg(result?.desc || '视频融合失败');
    return false;
}

// 视频融合 - 新增
function insertVideoFuse([one, ...other] = []) {
    const { projectAreaCode, projectAreaName, projectCode, projectName } = one;
    const videoFuseDetails = [one, ...other].map(item => ({
        equipmentInfo: JSON.stringify(item),
        equipmentId: item.equipmentCode,
    }));
    return emergencyRequest.insertVideoFuse({
        projectCode, projectName,
        projectAreaCode, projectAreaName,
        // fuseCode,
        fuseName: '视频拼接',
        videoFuseDetails,
    })
}

// 视频融合 - 修改
function updateVideoFuse(form, fuseDetails) {
    const videoFuseDetails = fuseDetails.map(item => ({
        equipmentInfo: JSON.stringify(item),
        equipmentId: item.equipmentCode,
    }));
    const options = { ...form, id, videoFuseDetails, projectCode, projectName, fuseName, fuseCode };

    return emergencyRequest.updateVideoFuse(options).then(() => {
        layer?.msg('更新成功！');
    })
}

// 视频融合 - 删除
function removeVideoFuse(id) {
    return emergencyRequest.removeVideoFuse(id).then(() => {
        layer?.msg('删除成功！');
    })
}

// 添加视频
async function addPlayer(data, index) {
    console.log(data, index, 'data, index')
    const widgets = helper.get('三维组件');
    const sullivan = widgets.widgetObj.sullivan;
    if (data.type === 'maintenance') {
        layer.msg('设备维修中');
        return;
    } else if (data.type === 'fuse') {
        const res = await getFuse(data);
        if (!res) return;
        sullivan.setPlayer({
            ...res,
            type: 'fuse',
            playerType: 'webrtc',
            equipmentName: data.fuseName,
            // 禁用 喊话
            shouting: false,
            // 禁用 3D变换
            threeD: false,
            // 禁用 云台
            movement: false,
            url: `${stream_url}/api/v1/stream/rtc/play`
        }, index);
    } else {
        if (!data.stream_path) {
            layer?.msg('未找到摄像头配置！');
            return;
        }
        sullivan.setPlayer({
            ...data,
            equipmentId: data.equipmentId || data.equipmentCode,
        }, index);
        widgets.widgetObj.addCameraContext(data.equipmentCode);
        return true;
    }
}

// 设置云台
function handlePtzCtrl(data) {
    const ptzCtrl = helper.get('ptz-ctrl', true);
    const [deviceId, channelId] = (data?.stream_path || '').split('/');
    if (deviceId && channelId) {
        helper.get('ptz-background', true);
        ptzCtrl.widgetObj.setPtzController({
            id: deviceId,
            channel: channelId,
            equipmentId: data.deviceId,
        })
    }
}

// 查询预置位
async function queryPrests(id) {
    // const loading = layer.load(0);
    let result = await iotServiceRequest.getPreset(id, videoPlatform);
    // layer.close(loading);
    if (!result) layer?.msg('获取预置位失败！');
    return (result?.list || []).map(item => ({
        ...item,
        sourceName: item.presetPointName,
        name: item.presetPointName,
        value: item.presetPointIndex
    }))
}

// 查询轮询/巡航
async function queryCruises(id) {
    // const loading = layer.load(0);
    let result = await iotServiceRequest.getCruiseRoute(id, videoPlatform);
    // layer.close(loading);
    return (result?.list || []).map(item => ({
        ...item,
        name: item.cruiseName,
        value: item.cruiseIndex
    }));
}

// 设置预置位信息
async function handlePresets(id) {
    const formObj = helper.get('form_14').widgetObj;
    // const data = formObj.getFormValue('form_14');
    // console.log(data, ' data')
    // const equipmentCode = data?.equipmentCode || '';
    let list = [];
    if (id) list = await queryPrests(id);
    formObj._option.options = { list };
    _videoAccess.controlData = { ..._videoAccess.controlData, type: 'preset', presetList: list };
    formObj.render();
    formObj.setFormData('form_14', { id });

    // 显示【预置位编辑】弹窗
    helper.getByCls('opts-form', true);

    const ptzTabObj = helper.get('ptz_tabs')?.widgetObj;
    ptzTabObj._option.defaultKey = 'preset';
    ptzTabObj.render();

    // 隐藏设置守望点
    helper.get('form_watch_out').hideWidget();

    const $play = helper.get('play');
    window._videoAccess.handleDisable($play.widgetObj.container, true);
    $play.widgetObj.container.setAttribute('title', '转到预置位');
    const $edit = helper.get('edit');
    window._videoAccess.handleDisable($edit.widgetObj.container, true);
    $edit.widgetObj.container.setAttribute('title', '设置预置位');
    const $clear = helper.get('clear');
    $clear.widgetObj.container.setAttribute('title', '清除预置位');
}

// 设置轮询/巡航信息
async function handleCruises(id) {
    const formObj = helper.get('form_14').widgetObj;
    // const data = formObj.getFormValue('form_14');
    let list = [];
    if (id) list = await queryCruises(id);
    formObj._option.options = { list };
    _videoAccess.controlData = { ..._videoAccess.controlData, type: 'cruise', cruiseList: list };
    formObj.render();
    formObj.setFormData('form_14', { id });

    // 显示【预置位编辑】弹窗
    helper.getByCls('opts-form', true);
    // 隐藏设置守望点
    helper.get('form_watch_out', false);

    const $play = helper.get('play');
    window._videoAccess.handleDisable($play.widgetObj.container, true);
    $play.widgetObj.container.setAttribute('title', '开始轮巡');
    const $edit = helper.get('edit');
    window._videoAccess.handleDisable($edit.widgetObj.container, true);
    $edit.widgetObj.container.setAttribute('title', '设置轮巡路径');
    const $clear = helper.get('clear');
    $clear.widgetObj.container.setAttribute('title', '清除轮巡路径');
}

async function handleWatchOut(id) {
    const formWatchOut = helper.get('form_watch_out', true);
    formWatchOut.widgetObj.resetForm('form_watch_out');

    // 隐藏【预置位编辑】弹窗
    helper.getByCls('opts-form', false);

    helper.get('stop', false);

    let list = [];
    if (id) list = await queryPrests(id);
    const formObj = helper.get('form_14').widgetObj;
    formObj._option.options = { list: list.slice(0, 32) };
    formObj.render();
    formObj.setFormData('form_14', { id });

    console.log(videoPlatform, 'videoPlatform')
    if (videoPlatform !== 'media') {
        layer?.msg('暂不支持守望!');
        return;
    }
    const res = await iotServiceRequest.getParkAction(id);
    if (res.success) {
        const result = res.result || {};
        window._videoAccess.watchOut = { time: result?.parkTime, id: result.id };
    }
}

/**
 * 获取监控视图选中项 - [私有方法]
 */
function __getMonitorSelected () {
    const active = $('#monitor_tree .tree_node_active').attr('data-nodeobject');
    try {
        if (active) {
            return JSON.parse(active)
        }
    } catch (error) {
        console.error(error)
    }
}

// 视频调阅页面全局属性/方法
window._videoAccess = {
    tabs,
    proxy: prefix, // 请求前缀
    monitorSearch: '', // 视图搜索值
    monitorSelect: undefined, // 视图当前选中项
    equipmentSearch: '', // 设备搜索值
    equipmentStatus: void 0, // 设备状态
    watchOut: {}, // 守望信息
    baseRequest,
    handleMonitorData,
    handleSullivanData,
    handleEquipmentTreeData,
    /**
     * 获取设备树-区域列表
     *
     * @param areaId
     * @return {Promise<void>}
     */
    queryRootEquipmentAreaTree: async (areaId = '-1') => {
        try {
            const { areaRows, equipmentRows, fusesRows } = await queryQuotaByArea(areaId) || {};
            renderTree([...areaRows, ...equipmentRows, ...fusesRows], areaId);
            areaRows.map(area => {
                queryQuotaByArea(area.id).then(({ areaRows, equipmentRows, fusesRows }) => {
                    renderTree([...areaRows, ...equipmentRows, ...fusesRows], area.id);
                })
            })
        } catch (error) {
            helper.error?.('请求错误',  error)
        }
    },
    handleAreaData,

    // 融合视频
    handleEquipmentData,
    getFuse,
    getFuseByEquipmentInfo,
    insertVideoFuse,
    updateVideoFuse,
    removeVideoFuse,

    addPlayer,
    queryQuotaByArea,
    queryFuseData,

    controlData: {}, // 视频控制信息
    renderTree,
    handlePtzCtrl,
    handlePresets,
    handleCruises,
    handleWatchOut,

    ptzShow: false,
    /**
     * 切换云台显隐
     */
    togglePtzShow() {
        const ptzTitle = helper.get('ptz_title').widgetObj;
        const change = helper.get('change')?.widgetObj
        change._option.defaultKey = 'preset';
        change.render();

        if (_videoAccess.ptzShow) {
            $(ptzTitle.container).parent().css({ bottom: 255 });
            helper.getByCls('ptz-modal', true);
            helper.getByCls('opts-form', true);
            helper.get('form_144', false);
        }
    },

    /**
     * 按钮禁用
     *
     * @param dom
     * @param flag
     */
    handleDisable(dom, flag) {
        if (flag) {
            $(dom).css({ filter: 'invert(40%)', cursor: 'not-allowed', 'pointer-events': 'none' });
        } else {
            $(dom).css({ filter: 'unset', cursor: 'pointer', 'pointer-events': 'auto' });
        }
    },

    /**
     * 获取当前选中的视图
     *
     * @param callback
     */
    selectView (callback) {
        const monitorSelect = __getMonitorSelected();
        console.log(monitorSelect)
        if (monitorSelect) {
            if (monitorSelect.monitorLevel === 'root') {
                layer.msg('当前选择为分组，请选择视图！');
            } else {
                callback(monitorSelect);
            }
        } else {
            layer.msg('请选择视图！');
        }
    },
}